import React, { useEffect, useState } from "react";
import { useStore } from "@/store";
import Editor from "react-simple-code-editor";
import { highlight, languages } from "prismjs";
import "prismjs/components/prism-clike.min";
import "prismjs/components/prism-javascript.min";
import "prismjs/themes/prism.css";
import { Tooltip, Modal } from "antd";

const SlideContent = () => {
  const {
    slideList,
    currentSlideIndex,
    sildeBgType,
    sildeBgVal,
    sildeBgVal2,
    updateSlide,
  } = useStore();
  // 单个幻灯片
  const slideListItem = slideList?.[currentSlideIndex - 1] || [];

  const doubleClick = (typeItem, elementsIndex) => {
    document.dispatchEvent(
      new CustomEvent("passEvent", {
        detail: {
          type: typeItem,
          elementsIndex: elementsIndex,
        },
      })
    );
  };

  // 判断什么语言;python、c、javascript、java
  const detectLanguage = (code) => {
    // Simple language detection based on common patterns
    const pythonPatterns = [
      /^#!/,
      /\bdef\b/,
      /\bprint\(/,
      /\bimport\b.*\n/,
      /:\s*$/m,
    ];

    const cPatterns = [
      /#include/,
      /int\s+main\s*\(/,
      /printf\s*\(/,
      /scanf\s*\(/,
      /void\s+\w+\s*\(/,
    ];

    const jsPatterns = [
      /const\s+/,
      /let\s+/,
      /function\s+/,
      /=>/,
      /console\.log/,
    ];

    const javaPatterns = [
      /public\s+class\s+\w+/,
      /public\s+static\s+void\s+main\s*\(/,
      /System\.out\.println/,
      /System\.in\.read/,
      /new\s+\w+\s*\(/,
    ];

    let pythonScore = 0;
    let cScore = 0;
    let jsScore = 0;
    let javaScore = 0;

    javaPatterns.forEach((pattern) => {
      if (pattern.test(code)) javaScore++;
    });

    pythonPatterns.forEach((pattern) => {
      if (pattern.test(code)) pythonScore++;
    });

    cPatterns.forEach((pattern) => {
      if (pattern.test(code)) cScore++;
    });

    jsPatterns.forEach((pattern) => {
      if (pattern.test(code)) jsScore++;
    });

    if (javaScore > cScore && javaScore > jsScore && javaScore > pythonScore)
      return "Java";
    if (pythonScore > cScore && pythonScore > jsScore) return "Python";
    if (cScore > pythonScore && cScore > jsScore) return "C";
    return "JavaScript";
  };

  const deleteItemElement = (index) => {
    // 将slideListItem的elements属性复制到一个新的数组elementsBro中
    // eslint-disable-next-line no-unsafe-optional-chaining
    const elementsBro = [...slideListItem?.elements];
    // 从elementsBro数组中删除指定索引的元素
    elementsBro.splice(index, 1);
    // 将slideList复制到一个新的数组powerPointArrBro中
    const powerPointArrBro = [...slideList];
    // 在powerPointArrBro数组中查找slideListItem的id，并返回其索引
    const indexFlag = powerPointArrBro.findIndex(
      (item) => item?.id === slideListItem?.id
    );
    // 如果找到了slideListItem的id，则从powerPointArrBro数组中删除指定索引的元素
    if (indexFlag !== -1) {
      powerPointArrBro[indexFlag].elements.splice(index, 1);
    }
    // 更新slideList数组
    updateSlide(powerPointArrBro);
  };

  return (
    <div style={{ height: "100%", overflowY: "auto" }}>
      <div
        key={currentSlideIndex}
        style={{
          position: "relative",
          display: "flex",
          flexDirection: "row",
          flexWrap: "wrap",
          justifyContent: "space-between",
          width: "1100px",
          height: "550px",
          margin: "auto",
          marginTop: "50px",
          padding: "16px 32px",
          overflow: "hidden",
          backgroundColor: "white",
          boxShadow:
            "0 1px 2px 0 rgba(0, 0, 0, 0.13), 0 1px 6px -1px rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.12)",
          // backgroundImage: `url(${slideListItem?.backgroundUrl})`,
          // background: `url(https://static.699pic.com/images/diversion/083dc8a89d003bc8d5f6bb24c2c4077d.jpg)`, // 设置背景图片
          background:
            slideListItem?.sildeBgType == "gradient"
              ? `linear-gradient(to bottom right,${slideListItem?.sildeBgVal},${slideListItem?.sildeBgVal2})`
              : slideListItem?.sildeBgType == "img"
              ? `url(${slideListItem?.sildeBgVal}) 0% 0% / cover no-repeat`
              : slideListItem?.sildeBgVal || "#fff",
          backgroundSize: "cover", // 设置背景图片大小
          backgroundRepeat: "no-repeat", // 设置背景图片不重复
        }}
      >
        {slideListItem?.elements?.map((item, index) => {
          // 文本
          if (item.type === "Text") {
            return (
              <div
                onContextMenu={(e) => {
                  e.preventDefault();
                  Modal.confirm({
                    title: "确认删除",
                    content: "确定要删除该代码元素吗？",
                    okText: "确定",
                    cancelText: "取消",
                    onOk: () => {
                      deleteItemElement(index);
                    },
                  });
                }}
                onDoubleClick={() => {
                  doubleClick("Text", index);
                }}
                key={item?.id}
                style={{
                  marginBottom: 16,
                  cursor: "pointer",
                  border: "1px solid #e8e8e8",
                  color: item?.fontColor || "#000000",
                  fontSize: `${item?.fontSize || 18}em`,
                  fontWeight: item?.fontWight || 800,
                  overflow: "hidden",
                  fontFamily: item?.fontFamily || "auto",
                  position: "absolute",
                  width: `${item?.blockWidth || 100}%`,
                  height: `${item?.blockHeight || 50}%`,
                  left: `${item?.xAxis || 0}%`,
                  top: `${item?.yAxis || 0}%`,
                }}
              >
                {item?.content}
              </div>
            );
          }
          // 图片
          if (item.type === "Image") {
            // asdas
            return (
              <div
                onContextMenu={(e) => {
                  e.preventDefault();
                  Modal.confirm({
                    title: "确认删除",
                    content: "确定要删除该图片元素吗？",
                    okText: "确定",
                    cancelText: "取消",
                    onOk: () => {
                      deleteItemElement(index);
                    },
                  });
                }}
                onDoubleClick={() => {
                  doubleClick("Image", index);
                }}
                style={{
                  marginBottom: 16,
                  cursor: "pointer",
                  position: "absolute",
                  width: `${item?.blockWidth || 100}%`,
                  height: `${item?.blockHeight || 50}%`,
                  left: `${item?.xAxis || 0}%`,
                  top: `${item?.yAxis || 0}%`,
                }}
                key={item.id}
              >
                <Tooltip title={item?.describe}>
                  <img
                    style={{
                      width: "100%",
                      height: "100%",
                    }}
                    src={item?.imageUrl}
                    alt={item?.describe}
                  />
                </Tooltip>
              </div>
            );
          }
          // 视频
          if (item.type === "Video") {
            return (
              <div
                key={currentSlideIndex}
                onDoubleClick={() => {
                  doubleClick("Video", index);
                }}
                style={{
                  marginBottom: 16,
                  cursor: "pointer",
                  position: "absolute",
                  width: `${item?.blockWidth || 100}%`,
                  height: `${item?.blockHeight || 50}%`,
                  left: `${item?.xAxis || 0}%`,
                  top: `${item?.yAxis || 0}%`,
                }}
                onContextMenu={(e) => {
                  e.preventDefault();
                  Modal.confirm({
                    title: "确认删除",
                    content: "确定要删除该视频元素吗？",
                    okText: "确定",
                    cancelText: "取消",
                    onOk: () => {
                      deleteItemElement(index);
                    },
                  });
                }}
              >
                <video
                  style={{
                    border: "1px solid #e8e8e8",
                    verticalAlign: "middle",
                    objectFit: "fill",
                  }}
                  width="100%"
                  height="100%"
                  controls
                  // 阻止默认的双击全屏行为
                  controlsList="nofullscreen"
                >
                  <source src={item?.videoUrl || 250} type="video/mp4" />
                  Your browser does not support the video tag.
                </video>
              </div>
            );
          }
          // 代码
          if (item.type === "Code") {
            return (
              <div
                onDoubleClick={() => {
                  doubleClick("Code", index);
                }}
                style={{
                  marginBottom: 16,
                  cursor: "pointer",
                  position: "absolute",
                  width: `${item?.blockWidth || 100}%`,
                  height: `${item?.blockHeight || 50}%`,
                  left: `${item?.xAxis || 0}%`,
                  top: `${item?.yAxis || 0}%`,
                }}
                key={item.id}
                onContextMenu={(e) => {
                  e.preventDefault();
                  Modal.confirm({
                    title: "确认删除",
                    content: "确定要删除该代码元素吗？",
                    okText: "确定",
                    cancelText: "取消",
                    onOk: () => {
                      deleteItemElement(index);
                    },
                  });
                }}
              >
                <div
                  style={{
                    width: "500px",
                    height: 250,
                    overflow: "hidden",
                    border: "1px solid #e8e8e8",
                    backgroundColor:
                      detectLanguage(item?.content) === "Python"
                        ? "#eef6ff"
                        : detectLanguage(item?.content) === "JavaScript"
                        ? "#fefce8"
                        : "#fbf5ff",
                  }}
                >
                  <div
                    style={{
                      width: "100%",
                      height: 40,
                      padding: "0 16px",
                      lineHeight: "38px",
                      borderBottom: "1px solid #e8e8e8",
                    }}
                  >
                    {detectLanguage(item?.content)}
                  </div>
                  <Editor
                    value={item?.content}
                    highlight={(code) =>
                      highlight(code, languages.js, "javascript")
                    }
                    padding={4}
                    style={{
                      display: "block",
                      width: "100%",
                      height: "100%",
                      overflow: "hidden",
                      border: "0px",
                      fontFamily: '"Fira code", "Fira Mono", monospace',
                      fontSize: item?.fontSize * 16 || 12,
                    }}
                    readOnly
                  />
                </div>
              </div>
            );
          }
          return null;
        })}
        <div
          style={{
            position: "absolute",
            bottom: 4,
            left: 4,
            color: "#bfbfbf",
            fontSize: 16,
          }}
        >
          {currentSlideIndex}/{slideList?.length}
        </div>
      </div>
    </div>
  );
};

export default SlideContent;
